package com.system.permissiondemo.controller;

import com.system.permissiondemo.common.RequestHolder;
import com.system.permissiondemo.common.ResultDTO;
import com.system.permissiondemo.entity.SysUser;
import com.system.permissiondemo.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/user")
@Api(tags = "用户业务管理")
@Slf4j
public class LoginController {

    @Autowired
    private SysUserService userService;

    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",value = "用户名", required = true, paramType = "query",dataType = "String",defaultValue = "joe"),
            @ApiImplicitParam(name = "password",value = "密码",required = true, paramType = "query",dataType = "String")
    })
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResultDTO login(HttpServletRequest request,String username,String password){
        SysUser sysUser = userService.findByKeyword(username);
        String errorMsg = "";
        if (StringUtils.isBlank(username)){
            errorMsg = "用户名不能为空";
        }else if (StringUtils.isBlank(password)){
            errorMsg = "密码不能为空";
        }else if (sysUser == null){
            errorMsg = "查询不到指定用户";
        }else if (!sysUser.getPassword().equals(password)){
            errorMsg = "用户名或密码错误";
        }else if (sysUser.getStatus() != 1){
            errorMsg = "用户已经被冻结，请联系管理员";
        }else {
            //登录成功业务
            RequestHolder.add(sysUser);
            request.getSession().setAttribute("user",sysUser);
            //可以在此指定跳转链接

        }

        if (StringUtils.isNotBlank(errorMsg)){
            return ResultDTO.errorOf(500,errorMsg);
        }
        return ResultDTO.okOf(sysUser);

    }
    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public ResultDTO logout(HttpServletRequest request){
        request.getSession().invalidate();
        return ResultDTO.okOf();
    }
}
